package icantalk.voip;

import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.JOptionPane;
import org.xiph.speex.SpeexDecoder;
import org.xiph.speex.SpeexEncoder;

/**
 * B2B Phone project
 *
 * @author Antonín Brettšnajdr
 */
class main extends javax.swing.JFrame {

    private static javax.swing.JLabel statusLabelStatic;

    static void setText(String string) {
        if (statusLabelStatic != null) {
            statusLabelStatic.setText(string);
        }
    }

    private DatagramSocket socket;
    private SoundIO snd;
    private SpeexEncoder speexEnc;
    private SpeexDecoder speexDec;
    private InetSocketAddress address;

    /** Creates new form main */
    public main(final String ip) {
        initComponents();
        statusLabelStatic = statusLabel;
        setLocationRelativeTo(null);
        statusLabel.setText("Waiting for connection to " + ip + " ...");

        new Thread(new Runnable() {

            @Override
            public void run() {
                connect(ip);

                statusLabel.setText("Connection established. Please wait a while ...");

                snd = new SoundIO();
                try {
                    snd.setUpMicrophone();
                    snd.setUpPlayback();
                    snd.startRecording();
                    snd.startPlaying();
                } catch (LineUnavailableException ex) {
                    JOptionPane.showMessageDialog(null, "Cannot initialize sound card. Device is used by another application?");
                    System.exit(0);
                }

                runThreads();

            }

            private void runThreads() {
                //Threads for receiving and sending

                //receiving
                new Thread(new receiveThread(socket,snd)).start();
                //sending
                new Thread(new sendThread(socket,snd,address)).start();
              
            }
        }).start();

    }

    /**
     * Create tunnel
     * 
     * @param ip Remote address
     */
    private void connect(String ip) {
        try {
            UDPTunneler tun = new UDPTunneler(65000, ip, 65000);
            tun.createTunnel();
            socket = tun.socket;
            address = new InetSocketAddress(ip, 65000);
        } catch (IOException ex) {
            Logger.getLogger(main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        hangupButton = new javax.swing.JButton();
        statusLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("B2B Phone (Powered by JSpeex)");

        hangupButton.setText("Hangup");
        hangupButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hangupButtonActionPerformed(evt);
            }
        });
        jPanel1.add(hangupButton);

        statusLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        statusLabel.setText(" ");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 374, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void hangupButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hangupButtonActionPerformed
        System.exit(0);
    }//GEN-LAST:event_hangupButtonActionPerformed


    private byte[] encodeWithSPEEX(byte[] buff) {

        if (speexEnc == null) {
            speexEnc = new SpeexEncoder();
            speexEnc.init(1, 3, 8000, 1);
        }

        speexEnc.processData(buff, 0, buff.length);

        byte[] out = new byte[speexEnc.getProcessedDataByteSize()];
        speexEnc.getProcessedData(out, 0);

        return out;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        final String ip;

        if (args.length > 0) {
            ip = args[0];
        } else {
            ip = "0.0.0.0";
        }


        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new main(ip).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton hangupButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel statusLabel;
    // End of variables declaration//GEN-END:variables
}
